package com.lebang.controller.sys;

import com.alibaba.fastjson.JSONObject;
import com.lebang.common.Login;
import com.lebang.component.RedisClient;
import com.lebang.domain.MemberCashWithdrawal;
import com.lebang.entity.RequestHeaders;
import com.lebang.example.MemberCashWithdrawalExample;
import com.lebang.model.enums.CheckStatus;
import com.lebang.model.enums.ResultVo;
import com.lebang.model.enums.buss.TaskStatus;
import com.lebang.service.MemberNoticeService;
import com.lebang.service.MemberWalletService;
import com.lebang.service.sys.DictService;
import com.lebang.service.sys.MemberCashWithdrawalService;
import com.lebangweb.common.TextUtil;
import com.lebangweb.common.UUIDUtil;
import com.lebangweb.response.Callback;
import com.lebangweb.response.JsonData;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;


/**
 * 新提现
 *
 * @author hwq
 * @date 2020-05-19
 */
@Controller
@RequestMapping("/sys/membercashwithdrawal")
public class MemberCashWithdrawalController {
    @Autowired
    private MemberCashWithdrawalService baseService;
    @Autowired
    private DictService dictService;
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private MemberWalletService walletService;
    @Autowired
    private MemberNoticeService memberNoticeService;

    public static String ALI_CASH_RECORD = "ali_cash_record";

    @GetMapping("/list")
    public String list() {
        return "/membercashwithdrawal/list";
    }

    @GetMapping("/add")
    public String add(Long id, Model model) {
        MemberCashWithdrawal vo;
        if (id != null) {
            vo = baseService.selectById(id);
        } else {
            vo = new MemberCashWithdrawal();
        }
        model.addAttribute("item", vo);
        return "/membercashwithdrawal/edit";
    }


    @PostMapping("/edit")
    @ResponseBody
    public JsonData edit(MemberCashWithdrawal vo) {
        if (vo.getId() != null) {
            vo.setModifyTime(LocalDateTime.now());
            baseService.updateById(vo);
        } else {
            vo.setCreateTime(LocalDateTime.now());
            vo.setHasDeleted(0);
            baseService.insertModel(vo);
        }
        return Callback.success("success", "操作成功");
    }

    @Login
    @PostMapping("/delete")
    @ResponseBody
    public JsonData delete(Long id) {
        baseService.deleteById(id);
        return Callback.success("success", "操作成功");
    }

    @ApiOperation(value = "分页")
    @PostMapping("/list")
    @ResponseBody
    public JSONObject list(HttpServletRequest request, @RequestParam Integer page, @RequestParam Integer limit) {
        MemberCashWithdrawalExample example = new MemberCashWithdrawalExample();
        example.setOffset((page - 1) * limit.longValue());
        example.setLimit(limit);
        MemberCashWithdrawalExample.Criteria criteria = example.createCriteria();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("data", baseService.selectByExample(example));
        jsonObject.put("count", baseService.countByExample(example));
        return jsonObject;
    }

    @Login
    @RequestMapping(value = "/checkList", method = {RequestMethod.GET})
    public String checkList(Model model) {
        model.addAttribute("taskStatus", TaskStatus.values());
        model.addAttribute("cash_str", dictService.selectByKeyName("cash_msg").getKeyvalue());
        return "/membercashwithdrawal/check-list";
    }


    @Login
    @RequestMapping(value = {"/staff-list"}, method = {RequestMethod.GET})
    public String slaphappiest(Model model) {
        model.addAttribute("cash_str", dictService.selectByKeyName("cash_msg").getKeyvalue());
        return "/membercashwithdrawal/staff-list";
    }

    @Login
    @RequestMapping(value = {"/all-list"}, method = {RequestMethod.GET})
    public String alkalies(Model model) {
        model.addAttribute("cash_str", dictService.selectByKeyName("cash_msg").getKeyvalue());
        return "/membercashwithdrawal/all-list";
    }

    /**
     * 审核失败
     *
     * @param id
     * @param remark
     * @param session
     * @return
     */
    @Login
    @RequestMapping(value = {"/repulse"}, method = {RequestMethod.POST})
    @ResponseBody
    public JsonData repulse(Long id, @RequestParam("remark") String remark, HttpSession session) {
        String uuid = UUIDUtil.M();
        try {
            boolean lock = redisClient.tryGetDistributedLock("lock:tradepay:" + id, uuid, 10000);
            if (!lock) {
                return Callback.fail("2010", "该订单其他人处理中", null);
            }
            MemberCashWithdrawal record = baseService.selectById(id);
            if (record == null) {
                return Callback.fail("200", "记录不存在");

            }
            if (!record.getCheckStatus().equals(CheckStatus.FIN_CHECK.getIndex())
                    && !record.getCheckStatus().equals(CheckStatus.BUSS_CHECK.getIndex())) {
                return Callback.fail("201", "参数非法");
            }
            record.setCheckStatus(CheckStatus.FAIL.getIndex());
            record.setRemark(remark);
            record.setModifyTime(LocalDateTime.now());
            baseService.updateById(record);
            walletService.addFail(record.getMemberId());
            RequestHeaders requestHeaders = new RequestHeaders();
            requestHeaders.setImei(record.getImei());
            requestHeaders.setUserid(record.getMemberId());
            requestHeaders.setAppStore(record.getAppStore());
            requestHeaders.setIpAddr(record.getIpAddr());
            requestHeaders.setVersion(record.getVersion());
            requestHeaders.setMacAddr(record.getMacAddr());
            memberNoticeService.addNoticeAndPush("提现审核失败","您的提现审核失败了，请及时查看失败原因，重新提交申请",record.getMemberId(),requestHeaders);
            return Callback.success("200", "操作成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return Callback.fail("201", "参数非法");
        } finally {
            redisClient.releaseDistributedLock("lock:tradepay:" + id, uuid);
        }
    }

    /**
     * 业务员审核通过
     *
     * @param id
     * @return
     */
    @Login
    @PostMapping(value = {"/pass"})
    @ResponseBody
    public JsonData checkStatus(Long id,HttpSession session) {
        String uuid = UUIDUtil.M();
        try {
            boolean lock = redisClient.tryGetDistributedLock("lock:tradepay:" + id, uuid, 10000);
            if (!lock) {
                return Callback.fail("2010", "该订单其他人处理中", null);
            }
            MemberCashWithdrawal record = baseService.selectById(id);
            if (record == null) {
                return Callback.fail("200", "记录不存在");

            }
            if (!record.getCheckStatus().equals(1)) {
                return Callback.fail("201", "参数非法");
            }
            record.setCheckStatus(CheckStatus.FIN_CHECK.getIndex());
            record.setChecker( session.getAttribute("userid").toString());
            record.setModifyTime(LocalDateTime.now());
            baseService.updateById(record);
            return Callback.success("200", "操作成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return Callback.fail("201", "参数非法");
        } finally {
            redisClient.releaseDistributedLock("lock:tradepay:" + id, uuid);
        }

    }

    @Login
    @RequestMapping(value = {"/staff-getList"}, method = {RequestMethod.POST})
    @ResponseBody
    public JSONObject snaffles(@RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime star,
                               @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime end,
                               Integer page, Integer limit, String phone, Integer checkStatus, Integer method,
                               String icrad, String realName, String imei) {
        if (TextUtil.isEmpty(star, end)) {
            star = null;
            end = null;
        }
        if (TextUtil.isEmpty(phone)) {
            phone = null;
        }
        if (TextUtil.isEmpty(checkStatus)) {
            checkStatus = null;
        }
        if (TextUtil.isEmpty(method)) {
            method = null;
        }
        if (TextUtil.isEmpty(icrad)) {
            icrad = null;
        }
        if (TextUtil.isEmpty(realName)) {
            realName = null;
        }
        if (TextUtil.isEmpty(imei)) {
            imei = null;
        }
        page = (page - 1) * limit;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("data", baseService.page(star, end, page, limit, phone, checkStatus, method, icrad, realName, imei));
        jsonObject.put("count", baseService.count(star, end, phone, checkStatus, method, icrad, realName, imei));
        return jsonObject;
    }

    /**
     * 提现通过后转账给用户接口**
     * param
     * id   提现订单id
     * payType = 1 支付宝自动转账
     * payType = 3 人工转账
     * payType = 2 微信
     */
    @Login
    @RequestMapping(value = {"/staff-pay"}, method = {RequestMethod.POST})
    @ResponseBody
    public JsonData staffPay(HttpSession session, Integer payType, Long id, String mark) {
        String uuid = UUIDUtil.M();
        try {
            if (payType == null || id == null) {
                return Callback.fail("2010", "转账失败", null);
            }
            int i = 0;
            boolean lock = redisClient.tryGetDistributedLock("lock:tradepay:" + id, uuid, 10000);
            if (!lock) {
                return Callback.fail("2010", "该订单其他人处理中", null);
            }
            MemberCashWithdrawal record = baseService.selectById(id);
            if (record == null) {
                return Callback.fail("200", "记录不存在");
            }
            if (!record.getCheckStatus().equals(CheckStatus.FIN_CHECK.getIndex())) {
                return Callback.fail("201", "订单已审核");
            }
            ResultVo vo = baseService.checkSuccess(record, payType, mark, session.getAttribute("userid").toString());
            RequestHeaders requestHeaders = new RequestHeaders();
            requestHeaders.setImei(record.getImei());
            requestHeaders.setUserid(record.getMemberId());
            requestHeaders.setAppStore(record.getAppStore());
            requestHeaders.setIpAddr(record.getIpAddr());
            requestHeaders.setVersion(record.getVersion());
            requestHeaders.setMacAddr(record.getMacAddr());
            if(vo.isSuccess()){
                //redis加钱进去
                //tradeService.addInCashRedis(record.getMemberId(),record.getAmount());
                //mysql持久化
                walletService.outLayMoney(record.getMemberId(),record.getAmount());

                if(record.getMethod()==1){
                    //支付宝 1209600
                    if(!redisClient.exists(ALI_CASH_RECORD+":"+record.getMemberId())){
                        int aliCashRecordTime = dictService.selectIntByKeyName("ali_cash_record_time");
                        redisClient.set(ALI_CASH_RECORD+":"+record.getMemberId(),"1");
                        redisClient.expire(ALI_CASH_RECORD+":"+record.getMemberId(),aliCashRecordTime);
                    }
                }

                memberNoticeService.addNoticeAndPush("提现成功到账","您的提现到账了，请及时查收",record.getMemberId(),requestHeaders);
            }else{
                memberNoticeService.addNoticeAndPush("提现审核失败","您的提现审核失败了，请及时查看失败原因，重新提交申请",record.getMemberId(),requestHeaders);
            }

            return vo.isSuccess() ? Callback.success("200", vo.getMsg()) : Callback.fail("201", vo.getMsg());
        } catch (Exception e) {
            e.printStackTrace();
            return Callback.fail("2060", "转账失败", e.getMessage());
        } finally {
            redisClient.releaseDistributedLock("lock:tradepay:" + id, uuid);
        }

    }

}
